<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改销售订单主')" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: select2-css" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-order-edit" th:object="${salesOrder}">
            <input name="orderId" th:field="*{orderId}" type="hidden">
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">订单编号：</label>
                    <div class="col-sm-8">
                        <input name="orderCode" th:field="*{orderCode}" class="form-control" type="text" required>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">客户公司：</label>
                    <div class="col-sm-8">
                        <select name="customerId" class="form-control select2-hidden-accessible" required>
                            <option value="">请选择客户公司</option>
                            <option th:each="customer : ${customerList}" th:text="${customer.customerName}" th:value="${customer.customerId}" th:selected="${customer.customerId == salesOrder.customerId}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">商品名称：</label>
                    <div class="col-sm-8">
                        <select name="productId" id="productId" class="form-control select2-hidden-accessible" required>
                            <option value="">请选择商品</option>
                            <option th:each="product : ${productList}" th:text="${product.productName}" th:value="${product.productId}" th:data-category="${product.categoryId}" th:data-price="${product.unitPrice}" th:selected="${product.productId == salesOrder.productId}"></option>
                        </select>
                        <input name="productName" id="productName" type="hidden" th:value="${salesOrder.productName}">
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">商品类别：</label>
                    <div class="col-sm-8">
                        <select name="categoryId" id="categoryId" class="form-control">
                            <option value="">请选择类别</option>
                            <option th:each="category : ${categoryList}" th:text="${category.dictLabel}" th:value="${category.dictValue}" th:selected="${category.dictValue == salesOrder.categoryId}"></option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">销售数量：</label>
                    <div class="col-sm-8">
                        <input name="quantity" id="quantity" class="form-control" type="number" min="1" th:value="${salesOrder.quantity}" required onchange="calculateTotal()">
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">销售单价：</label>
                    <div class="col-sm-8">
                        <input name="unitPrice" id="unitPrice" class="form-control" type="number" step="0.01" min="0.01" th:value="${salesOrder.unitPrice}" required onchange="calculateTotal()">
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">销售日期：</label>
                    <div class="col-sm-8">
                        <div class="input-group date">
                            <input name="orderDate" th:value="${#dates.format(salesOrder.orderDate, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text" required>
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">预计交货日期：</label>
                    <div class="col-sm-8">
                        <div class="input-group date">
                            <input name="expectedDeliveryDate" th:value="${#dates.format(salesOrder.expectedDeliveryDate, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text">
                            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">订单总金额：</label>
                    <div class="col-sm-8">
                        <input name="totalAmount" id="totalAmount" th:field="*{totalAmount}" class="form-control" type="text" readonly required>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">订单状态：</label>
                    <div class="col-sm-8">
                        <input type="hidden" name="orderStatus" value="0">
                        <input class="form-control" type="text" value="待审核" readonly>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label is-required">审核状态：</label>
                    <div class="col-sm-8">
                        <input type="hidden" name="auditStatus" value="0">
                        <input class="form-control" type="text" value="未审核" readonly>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">审核意见：</label>
                    <div class="col-sm-8">
                        <textarea name="auditOpinion" class="form-control">[[*{auditOpinion}]]</textarea>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">备注：</label>
                    <div class="col-sm-8">
                        <textarea name="remark" class="form-control">[[*{remark}]]</textarea>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">创建者：</label>
                    <div class="col-sm-8">
                        <input class="form-control" type="text" th:value="*{createdBy}" readonly>
                        <input name="createdBy" type="hidden" th:field="*{createdBy}">
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">创建时间：</label>
                    <div class="col-sm-8">
                        <input class="form-control" type="text" th:value="${#dates.format(salesOrder.createdTime, 'yyyy-MM-dd')}" readonly>
                        <input name="createdTime" type="hidden" th:value="${#dates.format(salesOrder.createdTime, 'yyyy-MM-dd')}">
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">更新者：</label>
                    <div class="col-sm-8">
                        <input class="form-control" type="text" th:value="${#session.getAttribute('loginName')}" readonly>
                        <input name="updatedBy" type="hidden" th:value="${#session.getAttribute('loginName')}">
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <label class="col-sm-3 control-label">更新时间：</label>
                    <div class="col-sm-8">
                        <input class="form-control" type="text" th:value="${#dates.format(#dates.createNow(), 'yyyy-MM-dd')}" readonly>
                        <input name="updatedTime" type="hidden" th:value="${#dates.format(#dates.createNow(), 'yyyy-MM-dd')}">
                    </div>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: select2-js" />
    <script th:inline="javascript">
        var prefix = ctx + "sales/order";
        $("#form-order-edit").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                // 提交前设置商品名称
                var productName = $("#productId").find("option:selected").text();
                $("#productName").val(productName);
                
                // 提交前检查库存
                checkStock(function(isStockSufficient) {
                    if (isStockSufficient) {
                        $.operate.save(prefix + "/edit", $('#form-order-edit').serialize());
                    }
                });
            }
        }

        $("input[name='orderDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $("input[name='expectedDeliveryDate']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $("input[name='createdTime']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $("input[name='updatedTime']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });
        
        $(function() {
            // 初始化select2
            $(".select2-hidden-accessible").select2({
                placeholder: "请选择",
                allowClear: true
            });
            
            // 商品选择事件
            $("#productId").change(function() {
                var selectedOption = $(this).find("option:selected");
                var categoryId = selectedOption.data("category");
                var unitPrice = selectedOption.data("price");
                
                // 设置商品类别
                $("#categoryId").val(categoryId);
                
                // 设置单价
                if (unitPrice) {
                    $("#unitPrice").val(unitPrice);
                } else {
                    $("#unitPrice").val("");
                }
                
                // 计算总价
                calculateTotal();
                
                // 检查库存
                checkStock();
            });
            
            // 数量变更事件
            $("#quantity").change(function() {
                // 计算总价
                calculateTotal();
                
                // 检查库存
                checkStock();
            });
            
            // 初始计算总价
            calculateTotal();
            
            // 初始检查库存
            checkStock();
        });
        
        // 计算订单总金额
        function calculateTotal() {
            var quantity = parseFloat($("#quantity").val()) || 0;
            var unitPrice = parseFloat($("#unitPrice").val()) || 0;
            var total = quantity * unitPrice;
            $("#totalAmount").val(total.toFixed(2));
        }
        
        // 检查库存是否足够
        function checkStock(callback) {
            var productId = $("#productId").val();
            var quantity = parseInt($("#quantity").val()) || 0;
            
            if (!productId || productId === "" || quantity <= 0) {
                // 如果没有选择商品或数量无效，不检查库存
                if (callback) callback(true);
                return;
            }
            
            // 移除之前的警告信息
            $("#stock-warning").remove();
            
            // 发送请求检查库存
            $.ajax({
                url: ctx + "sales/order/checkStock",
                type: "post",
                data: {
                    "productId": productId,
                    "quantity": quantity
                },
                dataType: "json",
                success: function(result) {
                    if (result.code === 0) {
                        // 库存充足
                        if (callback) callback(true);
                    } else {
                        // 库存不足，显示警告
                        var warningHtml = '<div id="stock-warning" class="col-xs-12"><div class="alert alert-warning">' +
                            '<i class="fa fa-warning"></i> ' + result.msg + '</div></div>';
                        $("#form-order-edit").prepend(warningHtml);
                        
                        if (callback) callback(false);
                    }
                },
                error: function() {
                    $.modal.alertError("检查库存失败，请稍后再试");
                    if (callback) callback(false);
                }
            });
        }
    </script>
</body>
</html>